<template>
  <div class="container">
    <h1>Pinia 持久化示例</h1>

    {{ address }}
    
    <!-- 计数器示例 -->
    <div class="card">
      <h2>计数器</h2>
      <p>当前计数: {{ counterStore.count }}</p>
      <p>双倍计数: {{ counterStore.doubleCount }}</p>
      <p>双倍计数加3: {{ counterStore.doubleCountPlus(3) }}</p>
      
      <a-space>
        <a-button type="primary" @click="counterStore.increment">增加</a-button>
        <a-button @click="counterStore.decrement">减少</a-button>
        <a-button status="danger" @click="counterStore.reset">重置</a-button>
        <a-button type="outline" @click="counterStore.incrementBy(10)">增加10</a-button>
      </a-space>
      
      <p class="note">刷新页面后计数器的值会保持不变，这是因为状态被持久化到了 localStorage</p>
    </div>
    
    <!-- 用户信息示例 -->
    <div class="card">
      <h2>用户信息</h2>
      <div v-if="userStore.isLoggedIn">
        <p>用户名: {{ userStore.userInfo?.username }}</p>
        <p>邮箱: {{ userStore.userInfo?.email }}</p>
        <p>角色: {{ userStore.userInfo?.roles.join(', ') }}</p>
        <p>最后登录时间: {{ formatDate(userStore.lastLoginTime) }}</p>
        
        <a-space>
          <a-button status="danger" @click="userStore.logout">退出登录</a-button>
          <a-button type="outline" @click="updateEmail">更新邮箱</a-button>
        </a-space>
      </div>
      <div v-else>
        <p>当前未登录</p>
        <a-button type="primary" @click="login">模拟登录</a-button>
      </div>
      
      <p class="note">刷新页面后登录状态会保持不变，这是因为用户信息被持久化到了 localStorage</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useCounterStore } from './stores/counter'
import { useUserStore } from './stores/user'
import { generateMockDeliveryAddress } from './libs/mock'
// 初始化 store
const counterStore = useCounterStore()
const userStore = useUserStore()

// 格式化日期
const formatDate = (timestamp: number | null) => {
  if (!timestamp) return '未知时间'
  return new Date(timestamp).toLocaleString()
}

const address = generateMockDeliveryAddress()

// 模拟登录
const login = () => {
  userStore.login({
    id: 1,
    username: '测试用户',
    email: 'test@example.com',
    token: 'fake-token-123456',
    roles: ['user', 'admin'],
  })
}

// 更新邮箱
const updateEmail = () => {
  userStore.updateUserInfo({
    email: `test${Date.now()}@example.com`
  })
}
</script>

<style scoped>
.container {
  max-width: 800px;
  margin: 50px auto;
  padding: 0 20px;
}

h1 {
  text-align: center;
  margin-bottom: 30px;
}

.card {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 30px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

h2 {
  margin-top: 0;
  margin-bottom: 20px;
  color: #333;
}

p {
  margin-bottom: 8px;
}

.note {
  margin-top: 20px;
  font-size: 14px;
  color: #666;
  font-style: italic;
}
</style>